

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
///使用场景：一般用于子组件对父组件传值。
class ParentWidget extends StatefulWidget {
  final String? title;

  ParentWidget({Key? key,this.title}):super(key: key);

  @override
  State<StatefulWidget> createState() {
    return ParentWidgetState();
  }

}

class ParentWidgetState extends State<ParentWidget>{

  Color containerBg = Colors.orange;
  //回调函数
  void changeBackgroundColor(Color newColor){
    setState(() {
      containerBg = newColor;//修改状态
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title??""),
      ),
      body: new Center(
        child: new GestureDetector(
          onTap: (){

          },
          child: new Container(
          width: 300,
          height: 300,
          color: containerBg,
          alignment: Alignment.center,
          child: new Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              childrenA(childrenABallback: changeBackgroundColor,),
              childrenB(childrenBBallback: changeBackgroundColor,),
            ],
          ),
        ),
        ),
      ),

    );
  }
  
}


///自组件 A
class childrenA extends StatelessWidget {

  final ValueChanged<Color>? childrenABallback;

  childrenA({Key? key,this.childrenABallback});

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: (){
        childrenABallback!(Colors.green);
      },
      child: new Container(
        width: 80,
        height: 80,
        color: Colors.green,
        child: new Text("ChildrenA"),
      ),
    );
  }

}



///自组件 A
class childrenB extends StatelessWidget {

  final ValueChanged<Color>? childrenBBallback;

  childrenB({Key? key,this.childrenBBallback});

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: (){
        childrenBBallback!(Colors.red);
      },
      child: new Container(
        width: 80,
        height: 80,
        color: Colors.red,
        child: new Text("ChildrenB"),
      ),
    );
  }

}
